import { computed, Ref } from "vue";
import {
  getWarehouseShipmentListApi,
  getWarehouseShipmentPageStatApi,
  quotationLogListApi,
  getOrderShipmentWarehouseListApi,
  enterWarehouseOrderApi,
  cancelWarehouseOrderApi,
  outShipmentApi,
  signWarehouseOrderApi,
  warehouseShipmentExcelApi
} from "@/api/waybillManagement/warehouseShipment";
import { message, message as Message } from "ant-design-vue";
import CommonHook from "@/hook/commonHook";

export default function OperationHook(state: {
  activeKey: Ref<string>;
  searchForm: WarehouseShipment.SearchForm;
  loading: Ref<boolean>;
  tableData: Ref<WarehouseShipment.ListRows[]>;
  pageStat: Ref<Base.GeneraDataType>;
  tableRef: Ref<any>;
  drawerOpts: Base.DrawerOpts;
}) {
  const { activeKey, searchForm, loading, tableData, pageStat, tableRef, drawerOpts } = state;
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { getNoZeroKey, downloadFileByBlob } = CommonHook();

  const getData = async () => {
    const params = {
      ...getParams()
    };

    loading.value = true;
    let requestFn;
    if (activeKey.value === "0") {
      requestFn = getOrderShipmentWarehouseListApi;
    } else requestFn = getWarehouseShipmentListApi;
    return requestFn(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = {
      ...getParams()
    };
    Reflect.deleteProperty(params, "status");
    return getWarehouseShipmentPageStatApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          0: data[0],
          1: data[1],
          2: data[2],
          3: data[3],
          4: data[4]
        });

        activeKey.value = String(getNoZeroKey(pageStat.value, ["0", "1", "2", "3", "4"]));
      }
    });
  };

  const getParams = () => {
    const {
      waybillNumList,
      fbaNumberList,
      transferOrderNumberList,
      warehouseCodeList,
      customerIdList,
      companyId,
      zipCode,
      bizIdList,
      followIdList,
      warehouseBillNumList,
      pageNum,
      pageSize,
      companyIdList
    } = searchForm;
    const params: Parameters<typeof getWarehouseShipmentListApi>[0] = {
      waybillNumList: [],
      fbaNumberList: [],
      transferOrderNumberList: [],
      warehouseCodeList,
      customerIdList,
      companyId,
      bizIdList,
      followIdList,
      warehouseBillNumList: [],
      companyIdList,
      status: activeKey.value === "0" ? undefined : Number(activeKey.value),
      pageNum,
      pageSize,
      zipCode: zipCode ? zipCode : undefined
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (fbaNumberList)
      params.fbaNumberList = fbaNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");

    if (transferOrderNumberList)
      params.transferOrderNumberList = transferOrderNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (warehouseBillNumList)
      params.warehouseBillNumList = warehouseBillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };

  const changeTabHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };
  //制作发票
  const makeInvoiceHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选数据！");
    if (selectRows.value.length > 1) return Message.error("只能勾选一条数据");

    drawerOpts.title = `制作发票`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "MakeInvoice";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };

  //确认运单信息
  const detailHandle = (row: Base.GeneraDataType) => {
    drawerOpts.title = `确认运单信息`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Detail";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };

  const showLogHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选数据！");
    drawerOpts.title = `账单日志`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "OperationLog";
    drawerOpts.passData = selectRows.value;
    drawerOpts.visible = true;
  };

  //下单确定
  const defineHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选数据！");
    enterWarehouseOrderApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        Message.success("操作成功");
        searchHandle();
      }
    });
  };

  //取消订单
  const cancelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选数据！");
    cancelWarehouseOrderApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        Message.success("操作成功");
        searchHandle();
      }
    });
  };
  //出运
  const outlHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选数据！");
    outShipmentApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        Message.success("操作成功");
        searchHandle();
      }
    });
  };
  //签收
  const signWarehouseOrderlHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选数据！");
    signWarehouseOrderApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        Message.success("操作成功");
        searchHandle();
      }
    });
  };
  //导出
  const exportHandle = () => {
    const params = {
      ...getParams(),
      idList: selectRows.value.length ? selectRows.value.map((t: any) => t.id) : undefined
    };
    return warehouseShipmentExcelApi(params).then((res: any) => {
      downloadFileByBlob(res, "海外仓运单.xlsx");
      message.success("下载成功!");
    });
  };

  const requestFn = () => {
    return quotationLogListApi(selectRows.value.map((t: any) => t.id));
  };

  return {
    getData,
    searchHandle,
    changeTabHandle,
    makeInvoiceHandle,
    showLogHandle,
    requestFn,
    defineHandle,
    cancelHandle,
    outlHandle,
    signWarehouseOrderlHandle,
    exportHandle,
    detailHandle
  };
}
